package top.llove.service.impl;

import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.llove.mapper.AdminMapper;
import top.llove.pojo.Admin;
import top.llove.service.AdminService;
import top.llove.utils.time.TimeUtils;
import top.llove.utils.res.ApiResult;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 管理员Service
 * @author: 幸会
 * @date: 2021/6/8 10:43
 * @email: 1846724873@qq.com
 * @description: 管理员Service
 * version: 1.0
 */
@Service
@Slf4j
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper admin; // 管理员Mapper

    @Autowired
    private ApiResult res; // 返回结果

    @Autowired
    private RedisTemplate redisTemplate; // Redis


    /**
     * 管理员注册
     * @param user 用户名
     * @param pass 密码
     * @param head 头像
     * @param email 邮箱
     * @return
     */
    @Override
    public ApiResult save(String user, String pass, String head, String email) {

        boolean ok = false;
        try {
            String password = DigestUtils.md5Hex(pass);
            log.info("MD5加密管理员密码: 加密前: " + pass + ", 加密后: " + password);
            ok = admin.save(user, password, head, email) == 1;
            res = ApiResult.success(200, "注册" + (ok ? "成功" : "失败"), ok);
            log.info("管理员注册： " + res);
        } catch (Exception e) {
            res = ApiResult.fail(500, "注册失败", e.getMessage());
        }
        return res;
    }

    /**
     * 管理员登录
     * @param user 用户名
     * @param pass 密码
     * @param verify 验证码
     * @param req 请求Request
     * @return
     */
    @Override
    public ApiResult login(String user, String pass, String verify, HttpServletRequest req) {
        String ip = ServletUtil.getClientIP(req); // 获取请求IP
        String ipMd5 = DigestUtils.md5Hex(ip); // 将ip进行MD5加密
        String code = (String) redisTemplate.opsForValue().get(ipMd5); // 获取验证码
        // 判断验证码是否为空
        if (verify != null && verify != "") {
            // 忽略大小写，对比验证码
            if (code.equalsIgnoreCase(verify)) {
                // 验证码对比完成后，删除Redis数据库的验证码
                Boolean delete = redisTemplate.delete(ipMd5);
                String password = DigestUtils.md5Hex(pass); // MD5加密用户输入密码
                log.info("登录加密密码，加密前：" + pass + "，加密后：" + password);
                List<Admin> login = admin.login(user, password);// 登录
                log.info("获取到登录信息：" + login);
                // 判断用户数量
                if (login.size() == 1) {
                    Admin adminInfo = login.get(0);
                    // 获取当前时间
                    String time = TimeUtils.getTime(0, "yyyy-MM-dd HH:mm:ss");
                    log.info("管理员: " + adminInfo.getUser() + ", 登陆时间为: " + time);
                    // 登录成功后修改管理员登陆时间
                    Integer update = admin.update(adminInfo.getId(), null, null, null, time);
                    log.warn(update == 1 ? "成功" : "失败" + "修改管理员登陆时间");

                    // 定义登陆成功返回结果
                    Map<String, Object> map = new HashMap<>();
                    // 将用户信息进行MD5加密
                    String userMd5 = DigestUtils.md5Hex(adminInfo.toString());
                    redisTemplate.opsForValue().set(userMd5, adminInfo, 60, TimeUnit.MINUTES);
                    log.info("登录成功，登录信息：token：" + userMd5 + "，用户信息：" + login);
                    map.put("token", userMd5);
                    map.put("status", true);
                    map.put("user", adminInfo);
                    res = ApiResult.success(200, "登陆成功", map);
                } else {
                    res = ApiResult.fail(400, "登陆失败", false);
                }
            } else {
                res = ApiResult.fail(400, "验证码错误", false);
            }
        } else {
            res = ApiResult.fail(400, "验证码不能为空", false);
        }

        return res;
    }

    /**
     * 修改管理员信息
     * @param id 管理员id
     * @param pass 密码
     * @param head 头像
     * @param email 邮箱
     * @return
     */
    @Override
    public ApiResult update(String id, String pass, String head, String email) {
        boolean ok = false;
        try {
            String password = DigestUtils.md5Hex(pass);
            log.info("加密前的密码: " + pass + ", 加密后的密码: " + password);
            ok = admin.update(id, password, head, email, null) == 1;
            res = ApiResult.success(200, ok ? "修改成功" : "修改失败", ok);
        } catch (Exception e) {
            e.printStackTrace();
            res = ApiResult.fail(500, "修改失败, 错误信息：" + e.getMessage(), false);
        }
        return res;
    }

    @Override
    public ApiResult exit(HttpServletRequest req) {
        String token = req.getHeader("token");
        if (token != null && !"".equals(token)) {
            Boolean delete = redisTemplate.delete(token);
            res = delete ? ApiResult.success(200, "退出成功", true) : ApiResult.fail(500, "token不存在", false);
        } else {
            res = ApiResult.fail(500, "token不能为空", false);
        }
        return res;
    }


}
